import React, { useContext, useState } from "react"
import classNames from "classnames"
import { MenuContext } from ".."
import Icon from "../../Icon/index"

export interface SubMenuProps {
	index?: string
	title: string
	className?: string
}

const SubMenu: React.FC<SubMenuProps> = ({ index, title, children, className }) => {
	const context = useContext(MenuContext)
	const openedSubmenus = context.defaultOpenedSubMenus as string[]
	const isOpened = index && context.mode === "vertical" && openedSubmenus.includes(index)

	const [menuOpen, setOpen] = useState(isOpened)
	const classes = classNames("menu-item submenu-item", className, {
		"is-active": index === context.index,
	})
	const handleClick = (e: React.MouseEvent) => {
		e.preventDefault()
		setOpen(!menuOpen)
	}
	let timer: NodeJS.Timeout
	const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
		clearTimeout(timer)
		timer = setTimeout(() => {
			setOpen(toggle)
		}, 300)
	}
	const clickEvents =
		context.mode === "vertical"
			? {
					onClick: handleClick,
			  }
			: {}
	const hoverEvents =
		context.mode !== "vertical"
			? {
					onMouseEnter: (e: React.MouseEvent) => {
						handleMouse(e, true)
					},
					onMouseLeave: (e: React.MouseEvent) => {
						handleMouse(e, false)
					},
			  }
			: {}

	const renderChildren = () => {
		const subMenuClasses = classNames("viking-submenu", {
			"menu-opened": menuOpen,
		})
		const childrenComponent = React.Children.map(children, (child, subIndex) => {
			const childElement = child as React.FunctionComponentElement<SubMenuProps>
			if (childElement.type.displayName === "MenuItem") {
				return React.cloneElement(childElement, { index: index ? index + "-" + subIndex : "-" + subIndex })
			} else {
				console.warn("Warning: menu has a child which is not MenuItem component!")
			}
		})
		return <ul className={subMenuClasses}>{childrenComponent}</ul>
	}
	return (
		<li key="index" className={classes} {...hoverEvents}>
			<div className="submenu-title" {...clickEvents}>
				{title}
				<Icon icon="arrow-down" className="arrow-icon"></Icon>
			</div>
			{renderChildren()}
		</li>
	)
}

SubMenu.displayName = "SubMenu"

export default SubMenu
